package com.orchid.shop.manager.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.orchid.shop.model.entity.system.SysUser;
import com.orchid.shop.model.vo.common.Result;
import com.orchid.shop.model.vo.common.ResultCodeEnum;
import com.orchid.shop.utils.AuthContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //方法之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取请求方式
        String method = request.getMethod();
        if("OPTIONS".equals(method)){  //如果是跨域预检请求，直接放行
            return true;
        }

        //获取token
        String token = request.getHeader("token");
        if(StrUtil.isEmpty(token)){
            responseNoLoginInfo(response);
            return false;
        }

        //如果token不为空
        String sysUserInfo = redisTemplate.opsForValue().get("user:login" + token);
        if(StrUtil.isEmpty(sysUserInfo)){
            responseNoLoginInfo(response);
            return false;
        }

        //将用户数据存储到ThreadLocal中
        SysUser sysUser = JSON.parseObject(sysUserInfo, SysUser.class);
        AuthContextUtil.set(sysUser);

        //重置redis中的用户过期时间
        redisTemplate.expire("user:login" + token, 30, TimeUnit.MINUTES);

        //放行
        return true;

    }

    //响应208状态码给前端
    private void responseNoLoginInfo(HttpServletResponse response) {
        Result<Object> result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) writer.close();
        }
    }


    //方法完成之后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthContextUtil.remove();  // 移除threadLocal中的数据
    }
}
